<template>
  <a-modal title-align="start" :title="title" :mask-closable="false" v-model:visible="showvisible" @cancel="showvisible = false" :width="1000">
    <a-space>
      <div>
        <span>关键词：</span>
        <span class="highlight">{{ props.info.keywordText }}</span>
      </div>
      <a-select placeholder="选择店铺" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search v-model="form.shopId" @change="selShop" style="width: 200px; margin-left: 10px">
        <a-option v-for="(item, index) of shopList" :key="index" :value="item.id">{{ item.shopName }}</a-option>
      </a-select>
      <a-select placeholder="输入活动名称搜索" :trigger-props="{ autoFitPopupMinWidth: true }" :loading="activeLoading" @change="selActive" allow-search :show-extra-options="false" v-model="form.activeId" style="width: 200px" @search="getActiveList" :filter-option="false">
        <a-option v-for="(item, index) of activeList" :key="index" :value="item.campaignId">{{ item.campaignName }}</a-option>
      </a-select>
      <a-button type="primary" @click="addTable">添加</a-button>
    </a-space>

    <a-table class="table-two-line mt10" :data="list" :pagination="false" :scroll="{ x: '100%', y: '500px' }">
      <template #columns>
        <a-table-column title="序号" #cell="{ record, rowIndex }" :width="40">{{ rowIndex + 1 }}</a-table-column>
        <a-table-column title="店铺" #cell="{ record }" :width="60">
          <textLimit :rows="1" position="top" :val="$extract(record, 'shopInfo.shopName')" />
        </a-table-column>
        <a-table-column title="活动" #cell="{ record }" :width="60">
          <textLimit :rows="1" position="top" :val="$extract(record, 'activeInfo.campaignName')" />
        </a-table-column>
        <a-table-column title="广告组" #cell="{ record }" :width="140">
          <a-select placeholder="输入广告组名称" :trigger-props="{ autoFitPopupMinWidth: true }" @change="getGroupInfo($event, record)" :loading="adverGroupLoading" allow-search :show-extra-options="false" v-model="record.adverGroupId" style="width: 200px" @search="getAdverGroupList($event, record)" :filter-option="false">
            <a-option v-for="(item, index) of record.adverGroupList" :key="index" :value="item.adGroupId">{{ item.adGroupName }}</a-option>
          </a-select>
        </a-table-column>
        <a-table-column title="匹配类型" #cell="{ record }" :width="180">
          <a-checkbox-group direction="horizontal" v-model="record.matchType">
            <div v-if="props.title == '添加投放'">
              <div>
                <a-space>
                  <a-checkbox value="EXACT">精确</a-checkbox>
                  <div>
                    <div class="highlight">{{ getInfo(record.recommendation, 'EXACT').rangeMedian || '--' }}</div>
                    <div>
                      <span>{{ getInfo(record.recommendation, 'EXACT').rangeStart || '--' }}</span>
                      <span>~</span>
                      <span>{{ getInfo(record.recommendation, 'EXACT').rangeEnd || '--' }}</span>
                    </div>
                  </div>
                </a-space>
              </div>
              <div>
                <a-space>
                  <a-checkbox value="PHRASE">词组</a-checkbox>
                  <div>
                    <div class="highlight">{{ getInfo(record.recommendation, 'PHRASE').rangeMedian || '--' }}</div>
                    <div>
                      <span>{{ getInfo(record.recommendation, 'PHRASE').rangeStart || '--' }}</span>
                      <span>~</span>
                      <span>{{ getInfo(record.recommendation, 'PHRASE').rangeEnd || '--' }}</span>
                    </div>
                  </div>
                </a-space>
              </div>
              <div>
                <a-space>
                  <a-checkbox value="BROAD">广泛</a-checkbox>
                  <div>
                    <div class="highlight">{{ getInfo(record.recommendation, 'BROAD').rangeMedian || '--' }}</div>
                    <div>
                      <span>{{ getInfo(record.recommendation, 'BROAD').rangeStart || '--' }}</span>
                      <span>~</span>
                      <span>{{ getInfo(record.recommendation, 'BROAD').rangeEnd || '--' }}</span>
                    </div>
                  </div>
                </a-space>
              </div>
            </div>
            <div v-else>
              <a-checkbox value="NEGATIVE_EXACT">精确</a-checkbox>
              <a-checkbox value="NEGATIVE_PHRASE">词组</a-checkbox>
              <!-- <a-checkbox value="NEGATIVE_BROAD">广泛</a-checkbox> -->
            </div>
          </a-checkbox-group>
        </a-table-column>
        <!-- <a-table-column v-if="title == '添加投放'" title="建议竞价" #cell="{ record }" :width="60"></a-table-column> -->
        <a-table-column v-if="title == '添加投放'" :width="80">
          <template #title>
            <div>
              <span class="required">*</span>
              <span>关键词竞价(USD)</span>
            </div>
          </template>

          <template #cell="{ record }">
            <a-input-number v-model="record.suggestPrice" />
          </template>
        </a-table-column>
        <a-table-column title="操作" #cell="{ record, rowIndex }" :width="40">
          <a-button type="text" style="color: red" @click="list.splice(rowIndex, 1)">移除</a-button>
        </a-table-column>
      </template>
    </a-table>

    <template #footer class="modal-footer">
      <a-button @click="showvisible = false">取消</a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { onMounted, ref, computed } from 'vue'
  import { findShopMarketByParam } from '@/api/system'
  import { getCampaignList, adGroupList, batchCreateKeyword, batchCreateNegativeKeyword, keywordRecommendation, getAllCampaignList, getAllAdGroupList, getAllPortfoliosList } from '@/api/advert'
  import { getStartAndEndTime } from '../../common'
  import { Message } from '@arco-design/web-vue'
  import { active } from 'sortablejs'
  import AddDataPermission from '@/views/system/authority/components/addDataPermission.vue'
  let props = defineProps(['modelValue', 'title', 'info'])
  let emits = defineEmits(['save', 'update:modelValue'])
  let showvisible = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emits('update:modelValue', val)
    },
  })

  let addItemObj: any = {
    shopInfo: {},
    activeInfo: {},
  }

  let activeLoading = ref(false)
  let adverGroupLoading = ref(false)
  let submitLoading = ref(false)
  let list = ref([])
  let adverGroupList = ref([])
  let form = ref({
    shopId: '',
    activeId: '',
  })
  let shopList = ref<Array<any>>([])
  let activeList = ref<Array<any>>([])

  const getShopList = async () => {
    let res = await findShopMarketByParam()
    shopList.value = res.data
  }

  const getActiveList = async (val: string) => {
    if (!form.value.shopId) return Message.error('请先选择店铺')
    if (val) {
      let params = {
        search: val,
        shopId: form.value.shopId,
      }
      activeLoading.value = true
      let res: any = await getAllCampaignList(params)
      activeLoading.value = false
      activeList.value = res.data || []
    }
  }

  const selShop = (id: string) => {
    let item = shopList.value.find((e: any) => e.id == id)
    if (item) {
      addItemObj.shopInfo = item
    }
    getActive()
  }

  const getActive = async () => {
    let params = {
      shopId: form.value.shopId,
    }
    const res: any = await getAllCampaignList(params)
    if (res) {
      activeList.value = res.data || []
    }
  }

  const selActive = (id: string) => {
    let item = activeList.value.find((e: any) => e.campaignId == id)
    if (item) {
      addItemObj.activeInfo = item
    }
  }

  const addTable = () => {
    if (!addItemObj.shopInfo.id) return Message.error('请先选择店铺')
    if (!addItemObj.activeInfo.campaignId) return Message.error('请先选择活动')

    let obj: any = {
      shopInfo: addItemObj.shopInfo,
      activeInfo: addItemObj.activeInfo,
      matchType: [],
      recommendation: [],
      adverGroupList: [],
    }
    getGroup(obj)
    if (props.title == '添加投放') {
      obj.suggestPrice = ''
      obj.keyWorldPrice = ''
      obj.matchType = ['EXACT', 'BROAD', 'PHRASE']
    } else {
      obj.matchType = ['NEGATIVE_EXACT', 'NEGATIVE_PHRAS']
    }
    list.value.push(obj)
    form.value.activeId = ''
    addItemObj.activeInfo = {}
    adverGroupList.value = []
    activeList.value = []
  }

  const getGroup = async (data: any) => {
    let params = {
      campaignId: form.value.activeId,
      shopId: form.value.shopId,
    }
    const res: any = await getAllAdGroupList(params)
    data.adverGroupList = res?.data || []
  }

  const getGroupInfo = (val: string, data: any) => {
    let item = data.adverGroupList.find((e: any) => e.adGroupId == val)
    if (item) {
      data.adverGroupInfo = item
    }

    if (props.title == '添加投放') getKeywordRecommendation(data)
  }

  const getAdverGroupList = async (val: string, data: any) => {
    if (val) {
      let params = {
        search: val,
        campaignId: data.activeInfo.campaignId,
        shopId: form.value.shopId,
      }
      adverGroupLoading.value = true
      let res: any = await getAllAdGroupList(params)
      adverGroupLoading.value = false
      adverGroupList.value = res.data?.data || []
    }
  }

  const submit = () => {
    console.log(props.title)

    props.title == '添加投放' ? createKeyWord() : createNegativeKeyword()
  }

  const createNegativeKeyword = async () => {
    try {
      let params: any = []
      list.value.forEach((e: any) => {
        let obj: any = {
          adGroupId: e.adverGroupInfo?.adGroupId || '',
          adType: e.activeInfo.adType,
          campaignId: e.activeInfo.campaignId,
          negativeKeywordInfos: [],
          shopId: e.shopInfo.id,
        }
        e.matchType.forEach((el: any) => {
          let obj1 = {
            keywordText: props.info.keywordText,
            matchType: el,
          }
          obj.negativeKeywordInfos.push(obj1)
        })

        params.push(obj)
      })

      const res: any = await batchCreateNegativeKeyword(params)
      if (res) {
        Message.success('创建成功')
        emits('save')
        showvisible.value = false
      }
    } catch (error) {}
    submitLoading.value = false
  }

  const createKeyWord = async () => {
    for (let i = 0; i < list.value.length; i++) {
      const e: any = list.value[i]
      if (e.suggestPrice == '') {
        return Message.error(`序号为${i + 1}的数据竞价必填`)
      }
    }

    try {
      let params: any = []
      list.value.forEach((e: any) => {
        let obj: any = {
          adType: e.activeInfo.adType,
          createKeywordInfos: [],
          shopId: e.shopInfo.id,
        }
        e.matchType.forEach((el: any) => {
          let obj1 = {
            adGroupId: e.adverGroupInfo?.adGroupId || '',
            bid: e.suggestPrice,
            campaignId: e.activeInfo.campaignId,
            keyword: props.info.keywordText,
            keywordMatchType: el,
          }
          obj.createKeywordInfos.push(obj1)
        })

        params.push(obj)
      })

      const res: any = await batchCreateKeyword(params)
      if (res) {
        Message.success('创建成功')
        emits('save')
        showvisible.value = false
      }
    } catch (error) {}
    submitLoading.value = false
  }

  async function getKeywordRecommendation(info: any) {
    let params: any = []
    let matchType = ['EXACT', 'PHRASE', 'BROAD']
    matchType.forEach((el: any) => {
      let otherObj =
        info.activeInfo.adType == 'SPONSORED_PRODUCTS'
          ? {
              spKeywordRecommendationType: 'KEYWORDS_FOR_ADGROUP',
              sortDimension: 'CONVERSIONS',
            }
          : {}
      params.push({
        shopId: info.shopInfo.id,
        shopKeywordInfo: {
          adGroupId: info.adverGroupInfo.adGroupId,
          adType: info.activeInfo.adType,
          campaignId: info.activeInfo.campaignId,
          keywordInfoBOs: [
            {
              keyword: props.info.keywordText,
              matchType: el,
            },
          ],
          maxRecommendations: 0,
          ...otherObj,
        },
      })
    })
    const res: any = await keywordRecommendation(params)
    info.recommendation = res?.data || []
  }

  const getInfo = (list: any, type: string) => {
    let item = list.find((e: any) => e.keywordInfos[0].matchType == type)
    if (item) {
      return item.keywordInfos[0]
    } else {
      return {}
    }
  }

  onMounted(() => {
    getShopList()
  })
</script>

<style lang="less" scoped></style>
